class Solution
{
public:
    int numOfMinutes(int n, int headID, vector<int> &manager, vector<int> &informTime)
    {
        vector<unordered_set<int>> children(n);
        for (int i = 0; i < n; ++i)
        {
            if (manager[i] != -1)
            {
                children[manager[i]].insert(i);
            }
        }

        queue<pair<int, int>> q;
        q.push({headID, 0});
        int maxTime = 0;

        while (!q.empty())
        {
            auto [id, curTime] = q.front();
            maxTime = max(maxTime, curTime);
            q.pop();
            for (int child : children[id])
            {
                q.push({child, curTime + informTime[id]});
            }
        }
        return maxTime;
    }
};